import axios, {
  AxiosInstance,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from 'axios'
import { BaseResponse } from '@/api/interface'
import NProgress from '@/config/nprogress'
export const instance: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API || '',
  timeout: 60000, // 增加到60秒，因为AI生成需要较长时间
  // withCredentials: true,
})


let requestCount = 0

function handleDone() {
  requestCount--
  if (requestCount === 0) NProgress.done()
}

// 请求拦截器
instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 开启进度条
    if (requestCount === 0) NProgress.start()
    requestCount++

    return config
  },
  (error) => Promise.reject(error)
)

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data } = response
    handleDone()
    return data
  },
  (error) => {
    handleDone()
    return Promise.reject(error)
  }
)


// 封装get方法
export const httpGet = <T>(
  url: string,
  params?: object
): Promise<T> => instance.get(url, { params })

// 获取二进制(音频/文件) - GET
export const httpGetBlob = (
  url: string,
  params?: object
): Promise<Blob> => instance.get(url, { params, responseType: 'blob' })

// 封装post方法
export const httpPost = <T>(
  url: string,
  data?: object,
  header?: object
): Promise<BaseResponse<T>> => instance.post(url, data, header)

// 封装upload方法
export const httpUpload = <T>(
  url: string,
  formData: FormData,
  header?: object
): Promise<BaseResponse<T>> => {
  return instance.post(url, formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
      ...header,
    },
  })
}
